<script setup>
import { ref, onMounted, onUnmounted, computed } from "vue";
// 导入全局变量
import useGlobalProperties from "@/hooks/globalVar";
import { usersData } from "@/api/api";
import AL02 from "@/assets/images/location/AL02.jpg";
import AL03 from "@/assets/images/location/AL03.jpg";
import AL04 from "@/assets/images/location/AL04.jpg";
import AL05 from "@/assets/images/location/AL05.jpg";
import AL06 from "@/assets/images/location/AL06.jpg";
import AL08 from "@/assets/images/location/AL08.jpg";
import AL09 from "@/assets/images/location/AL09.jpg";
import AL10 from "@/assets/images/location/AL10.jpg";

import Diriyah from "@/assets/images/location/Diriyah-1.jpg";
import Murabba from "@/assets/images/location/New-Murabba-2.jpg";
import Park01 from "@/assets/images/location/Park01.jpg";
import Park02 from "@/assets/images/location/Park02.jpg";

import galley01 from "@/assets/images/big/galley-1.jpg"; // Park
import galley02 from "@/assets/images/big/galley-2.jpg"; // Alsoudah
import galley03 from "@/assets/images/big/galley-3.jpg"; // Murabba
import galley04 from "@/assets/images/big/galley-4.jpg"; // Diriyah

// 获取全局变量
let baseImgUrl = useGlobalProperties().$baseImgUrl;

let socket = null;
const socketType = ref(""); // 1 Alsoudah, 2 Diriyah, 3 KingSalmanPark, 4 NewMurabba,
const step = ref(0); // 0，默认轮播 1 等待ipad选择场景 2生成中
const userData = ref([{}]); // 接口返回的数据
const totalCount = ref(0);
const currentLocation = computed(() => {
  console.log(socketType.value, "socketType.value");
  return {
    ...selectLocation[socketType.value],
    imgs: getRandomImgs(selectLocation[socketType.value].imgs),
  };
}); // 当前选择场景
// 随机取出4张图片
const getRandomImgs = (imgs) => {
  if (imgs.length < 4) {
    return imgs;
  }
  return imgs.sort(() => Math.random() - 0.5).slice(0, 4);
};

const commonTimer = ref(null);
const commonIndex = ref(0);
const stepIndex = ref(0);
const commonImgList = ref([galley01, galley02, galley03, galley04]);
const stepTimer = ref(null);
// 生成成功后的图片
const generationSuccess = ref({
  bgImgage: "",
  localname: "",
  image: "",
});
// ipad选择场景后，从这个数组取对应的type，进行页面图片和文案切换
const selectLocation = {
  Alsoudah: {
    title: "Alsoudah",
    desc: [
      "Soudah s a mountainous area in the Asir Province of Saudi Arabia. At 3,015 metres above sea level, it includes Saudi ",
      "Arabia’s highest peak, Jabal Soudah. The area is known for its dense juniper tree covered mountains.",
    ],
    imgs: [AL02, AL03, AL04, AL05, AL06, AL08, AL09, AL10],
  },
  KingSalmanPark: {
    title: "King Salman Park",
    desc: [
      "King Salman Park, one of Riyadh’s mega projects was unveiled in 2019 as part of the Green Riyadh initiative aimed at increasing the green space of Riyadh.",
      "It seamlessly blends urban vibrancy with natural tranquility, offering over 16km2 of diverse experiences, with its iconic Salmani-inspired architecture, rich biodiversity, and expansive green spaces. When completed, it will be one of the largest urban parks in the world.",
    ],
    imgs: [Park01, Park02],
  },
  NewMurabba: {
    title: "New Murabba",
    desc: [
      "New Murabba is a major mixed-use development in Riyadh. Its centerpiece, The Mukaab, a 400-meter cube-shaped skyscraper, will form part of the world’s second climate-controlled indoor city.",
      "Designed for sustainability and innovation, it will feature green spaces, walking and cycling paths, and over 80 cultural, educational, and entertainment venues, creating a vibrant, future-focused urban destination.",
    ],
    imgs: [Murabba],
  },
  Diriyah: {
    title: "Diriyah",
    desc: [
      "Diriyah, the birthplace of Saudi Arabia and ancestral home of the Al Saud family, is a symbol of national heritage and pride. Once the 18th-century capital of the first Saudi State, it shaped the Kingdom’s cultural and political foundations. ",
      "Today, centered around the UNESCO-listed At-Turaif, Diriyah is being reborn as a global cultural capital, where history, creativity, and innovation come together to celebrate Saudi Arabia’s enduring spirit",
    ],
    imgs: [Diriyah],
  },
};

onMounted(async () => {
  await usersData({}).then((res) => {
    let { data } = res.data;
    console.log(data, "data");
    userData.value = data.users.map((item) => {
      let bigImg = getImgByLocalname(item.localname);
      return {
        ...item,
        bigImg: bigImg,
      };
    });
    totalCount.value = data.total_count;
  });
  // 开启轮播图
  startCommonTimer();
  // 开启socket
  // startSocket();
});

// 根据localname获取图片
const getImgByLocalname = (localname) => {
  console.log(localname, "localname");
  if (localname === "alsoudah") {
    return galley02;
  }
  if (localname === "kingsalmanpark") {
    return galley01;
  }
  if (localname === "newmurabba") {
    return galley03;
  }
  return galley04;
};

const startSocket = () => {
  socket = io("http://b1740j1440.yicp.fun:47231/");
  console.log(socket.on, "socket");
  socket.on("connect", () => {
    console.log("socket connect 1");
    // 注册为大屏客户端
    socket.emit("register_client", { client_type: "large_screen" });
  });
  socket.on("disconnect", function () {
    console.log("WebSocket 已断开");
    // updateStatus("connection-status", "未连接", "#e74c3c");
  });

  socket.on("registered", function (data) {
    console.log("成功注册为大屏客户端: " + JSON.stringify(data));
  });

  socket.on("show_location_page", function (data) {
    console.log("显示景点页面: " + JSON.stringify(data));
    socketType.value = data.location_name;
    changeStep(1);
  });

  socket.on("show_generation_waiting", function (data) {
    console.log("显示生成等待页面: " + JSON.stringify(data));
    socketType.value = data.location_name;
    changeStep(2);
  });

  socket.on("generation_success", function (data) {
    console.log("显示生成成功: " + JSON.stringify(data));
    showGenerationSuccess(data.location_name, data.result_data);
  });

  socket.on("show_standby_page", function (data) {
    console.log("返回待机页面: " + JSON.stringify(data));
    changeStep(0);
  });

  socket.on("error", function (data) {
    console.log("错误: " + JSON.stringify(data));
  });
};
// 显示生成成功
const showGenerationSuccess = (location_name, result_data) => {
  console.log(location_name, result_data, "location_name, result_data");
  generationSuccess.value = {
    // 从当前场景中随机取一张图片
    bgImgage:
      currentLocation.value.imgs[
        Math.floor(Math.random() * currentLocation.value.imgs.length)
      ],
    localname: location_name, // 当前场景
    image: result_data, // 生成的图片
  };
  changeStep(3);
};

const startCommonTimer = () => {
  // 开启轮播图
  commonTimer.value = setInterval(() => {
    if (commonIndex.value === userData.value.length - 1) {
      commonIndex.value = 0;
    } else {
      commonIndex.value += 1;
    }
  }, 3000);
};
// 步骤1和2开启轮播图
const startStepTimer = () => {
  // 开启轮播图
  stepTimer.value = setInterval(() => {
    if (stepIndex.value === commonImgList.value.length - 1) {
      stepIndex.value = 0;
    } else {
      stepIndex.value += 1;
    }
  }, 3000);
};
// 切换步骤
const changeStep = (num) => {
  console.log(socketType.value, "------");
  step.value = num;

  if (step.value === 1 || step.value === 2) {
    clearInterval(commonTimer.value);
    commonIndex.value = 0;
    clearInterval(stepTimer.value);
    commonImgList.value = currentLocation.value.imgs;
    if (currentLocation.value.imgs.length > 1) {
      startStepTimer();
    } else {
      stepIndex.value = 0;
    }
  }
};

// 根据接口返回的localname，转换为中文
const conversionName = (name) => {
  if (name === "alsoudah") {
    return "Alsoudah";
  }
  if (name === "diriyah") {
    return "Diriyah";
  }
  if (name === "kingsalmanpark") {
    return "King Salman Park";
  }
  if (name === "newmurabba") {
    return "New Murabba";
  }
  return name;
};

const getLocationName = () => {
  alert(123);
  if (step.value === 3) {
    return generationSuccess.value.localname?.toLowerCase();
  }
};

onUnmounted(() => {
  clearTimeout(commonTimer.value);
});
</script>

<template>
  <div class="big home">
    <!-- 生成成功，默认展示一张背景图 -->
    <img
      v-show="step === 3"
      class="bg active"
      :src="generationSuccess.bgImgage"
    />
    <img
      v-show="step === 0"
      class="bg"
      :class="{ active: commonIndex === index }"
      v-for="(item, index) in userData"
      :key="index"
      :src="item.bigImg"
    />
    <img
      v-show="step !== 0"
      class="bg"
      :class="{ active: stepIndex === index }"
      v-for="(item, index) in commonImgList"
      :key="index"
      :src="item"
    />
    <!-- 步骤0 展示历史用户生成的景点页面 -->
    <div v-if="step === 0">
      <div class="left">
        <img class="left-bg" src="@/assets/images/big/left-bg.png" />
        <!-- Al soudah -->
        <div
          class="left-name"
          v-if="userData[commonIndex].localname === 'alsoudah'"
        >
          <span class="red">Al</span>
          <span>soudah</span>
        </div>
        <!-- King Salman Park -->
        <div
          class="left-name"
          v-if="userData[commonIndex].localname === 'kingsalmanpark'"
        >
          <span>King Salman</span>
          <span class="red"> Park</span>
        </div>
        <!-- New Murabba -->
        <div
          class="left-name"
          v-if="userData[commonIndex].localname === 'newmurabba'"
        >
          <span class="red">New </span>
          <span>Murabba</span>
        </div>
        <!-- Diriyah -->
        <div
          class="left-name"
          v-if="userData[commonIndex].localname === 'diriyah'"
        >
          <span class="red">D</span>
          <span>iriyah</span>
        </div>
      </div>
      <div class="right">
        <div class="title">Imaginary Destination</div>
        <div class="pic">
          <img :src="baseImgUrl + userData[commonIndex].generateimage" />
        </div>
        <div class="desc">
          <div class="name">
            <span>#</span>
            <span>{{ conversionName(userData[commonIndex].localname) }}</span>
          </div>
          <div class="name1">
            <span>#</span>
            <span>going_further_with_AI</span>
          </div>
          <div class="name1">
            <span>#</span>
            <span>solution_by_stc</span>
          </div>
        </div>
        <div class="vector">
          <img src="@/assets/images/big/vector.png" />
          <div class="num">{{ totalCount }}</div>
        </div>
      </div>
    </div>
    <!-- 步骤3 展示生成成功后的图片 -->
    <div v-if="step === 3">
      <div class="left">
        <img class="left-bg" src="@/assets/images/big/left-bg.png" />
        <!-- Al soudah -->
        <div class="left-name" v-if="getLocationName() === 'alsoudah'">
          <span class="red">Al</span>
          <span>soudah</span>
        </div>
        <!-- King Salman Park -->
        <div class="left-name" v-if="getLocationName() === 'kingsalmanpark'">
          <span>King Salman</span>
          <span class="red"> Park</span>
        </div>
        <!-- New Murabba -->
        <div class="left-name" v-if="getLocationName() === 'newmurabba'">
          <span class="red">New </span>
          <span>Murabba</span>
        </div>
        <!-- Diriyah -->
        <div class="left-name" v-if="getLocationName() === 'diriyah'">
          <span class="red">D</span>
          <span>iriyah</span>
        </div>
      </div>
      <div class="right">
        <div class="title">Imaginary Destination</div>
        <div class="pic">
          <img :src="generationSuccess.image" />
        </div>
        <div class="desc">
          <div class="name">
            <span>#</span>
            <span>{{ conversionName(generationSuccess.localname) }}</span>
          </div>
          <div class="name1">
            <span>#</span>
            <span>going_further_with_AI</span>
          </div>
          <div class="name1">
            <span>#</span>
            <span>solution_by_stc</span>
          </div>
        </div>
        <div class="vector">
          <img src="@/assets/images/big/vector.png" />
          <div class="num">{{ totalCount }}</div>
        </div>
      </div>
    </div>
    <!-- 等待ipad选择场景  -->
    <div
      class="right right-step"
      v-if="step === 1 || step === 2"
      :class="{ 'step-2': step === 2 }"
    >
      <div class="top">
        <div class="title-1">
          {{ currentLocation.title }}
        </div>
        <div class="title-desc">
          <div v-for="item in currentLocation.desc" :key="item">
            <span>{{ item }}</span>
          </div>
        </div>
        <div class="img-empty"></div>
        <div class="imgs-small">
          <template v-for="(img, index) in currentLocation.imgs" :key="img">
            <div
              class="item"
              v-if="
                currentLocation.imgs.length === 2 ||
                (currentLocation.imgs.length > 2 && index !== 0)
              "
              :key="img"
            >
              <img :src="img" />
            </div>
          </template>
        </div>
      </div>
      <div class="btn-box" v-if="step === 2">Generating, please wait…</div>
    </div>
  </div>
</template>

<style scoped lang="scss">
.home {
  display: flex;
}

.bg {
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0;
  left: 0;
  object-fit: cover;
  opacity: 0;
  transition: all 0.5s ease;
  &.active {
    opacity: 1;
  }
}

.change-step {
  position: absolute;
  top: 0;
  left: 0;
  z-index: 100;
  font-size: 30px;
  color: #fff;
  background: #f23153;
}
.left {
  position: absolute;
  bottom: 0;
  left: 0;
  width: calc(100% - 900px);
  height: 300px;
  .left-bg {
    position: absolute;
    bottom: 0;
    left: 0;
    width: 100%;
  }
  .left-name {
    position: absolute;
    left: 80px;
    width: 100%;
    bottom: 60px;
    font-family: "stc-bold";
    font-size: 120px;
    color: #fff;
    .red {
      color: #f23153;
    }
  }
}
.right {
  width: 900px;
  height: 100%;
  position: absolute;
  top: 0;
  right: 0;
  background: linear-gradient(
    180deg,
    rgba(69, 4, 126, 0.6) 0%,
    rgba(69, 4, 126, 1) 60%,
    #7d07e4 100%
  );
  .title {
    width: 100%;
    position: absolute;
    top: 74px;
    height: 180px;
    background: #fff;
    line-height: 180px;
    font-size: 70px;
    font-family: "stc-bold";
    color: #4f008c;
    text-align: center;
  }

  .pic {
    position: absolute;
    top: 254px;
    width: 100%;
    height: 675px;
    overflow: hidden;
    img {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }
  }
  .desc {
    position: absolute;
    top: 970px;
    padding-left: 50px;
    width: 100%;
    .name {
      font-size: 60px;
      font-family: "stc-medium";
      color: #fff;
      margin-bottom: 30px;
      span:first-child {
        font-family: "stc-bold";
        color: #f23153;
        margin-right: 10px;
      }
    }
    .name1 {
      font-size: 36px;
      font-family: "stc-regular";
      color: #fff;
      margin-bottom: 10px;
      span:first-child {
        font-family: "stc-bold";
        color: #f23153;
        margin-right: 10px;
      }
    }
  }
  .vector {
    position: absolute;
    bottom: 10px;
    right: 50px;
    display: flex;
    align-items: center;
    font-size: 0;
    .num {
      font-size: 50px;
      font-family: "stc-medium";
      color: #fff;
    }
    img {
      width: 46px;
      height: 40px;
      margin-right: 20px;
    }
  }
}
.btn-box {
  width: 100%;
  height: 180px;
  background: #fff;
  box-sizing: border-box;
  padding-left: 30px;
  line-height: 180px;
  font-size: 62px;
  color: #4f008c;
  font-family: "stc-medium";
}
.right-step {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: space-between;
  width: 900px;
  box-sizing: border-box;
  height: 100%;
  .top {
    flex: 1;
    width: 100%;
    overflow: hidden;
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    justify-content: center;
    padding-left: 50px;
    margin-bottom: 40px;
    box-sizing: border-box;
  }
  .title-1 {
    width: 100%;
    font-size: 90px;
    color: #fff;
    font-family: "stc-medium";
    margin-bottom: 30px;
  }
  .title-desc {
    font-size: 38px;
    color: #fff;
    font-family: "stc-light";
    margin-bottom: 30px;
    width: 800px;
  }
  .img-empty {
    width: 100%;
    height: 240px;
  }
  .imgs-small {
    display: flex;
    align-items: center;
    justify-content: flex-end;
    position: absolute;
    top: 940px;
    left: -520px;
    width: 1386px;
    .item {
      width: 432px;
      height: 240px;
      margin-left: 30px;
      overflow: hidden;
      img {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }
    }
  }
}

.step-2 {
  padding-bottom: 70px;
  .imgs-small {
    top: 770px;
  }
}
</style>
